package com.sixi.GeoTransfer;

import java.awt.Point;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.sixi.GeoTransfer.model.AreaModel;
import com.sixi.GeoTransfer.model.City;

public class KmlAnalyse {

	public static void main(String[] args) {
		try {
			//***************建立dom解析模式
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			
			//***************初始化文件流
			//***************获得中心点和城市名称
			File f = new File("./src/main/resources/yunnan_centre_point.kml");
			Document doc = builder.parse(f);
			NodeList nodeList = doc.getElementsByTagName("Folder");
			List<AreaModel> cityList = new ArrayList<AreaModel>();
			for(int i = 0 ; i < nodeList.getLength() ; i ++) {
				String name = nodeList.item(i).getFirstChild().getTextContent();
				if(name.equals("市级地名")) {
					NodeList childNodes = nodeList.item(i).getChildNodes();
					for(int j = 0 ; j < childNodes.getLength(); j ++) {
						City city = new City();
						String placeMark = childNodes.item(j).getNodeName();
						if(placeMark.equals("Placemark")) {
							NodeList placemarkChildNodes = childNodes.item(j).getChildNodes();
							for(int y = 0 ; y < placemarkChildNodes.getLength() ; y++) {
								if("name".equals(placemarkChildNodes.item(y).getNodeName())) {
									city.setName(placemarkChildNodes.item(y).getTextContent());
								}
								if("Point".equals(placemarkChildNodes.item(y).getNodeName())) {
									String[] point = placemarkChildNodes.item(y).getFirstChild().getTextContent().split(",");
									if(2== point.length) {
										Point.Double centre = new Point.Double(Double.parseDouble(point[0]), Double.parseDouble(point[1])) ;
										city.setCentre(centre);
										cityList.add(city);
									}
								}
							}
						}
					}
				}
			}

			//***************匹配邮编区号
			File f3 = new File("./src/main/resources/all_city.txt");
			BufferedReader br = null;
			br = new BufferedReader(new FileReader(f3));
			String temp;
			while ((temp = br.readLine()) != null) {
				String[] cityArray = temp.split("\\t");
				if(cityArray[5].equals("city")) {
					for(AreaModel ct : cityList) {
						if(ct.getName().equals(cityArray[6])) {
								ct.setCityCode(cityArray[4]);
								ct.setAdCode(cityArray[1]);
						}
					}
				}
				
			}
			
			
			
			//***************初始化文件输出流
			FileOutputStream out = null;
			out = new FileOutputStream(new File("./src/main/resources/china_city_info.tb"));
			
			//***************匹配边界信息
			File f2 = new File("./src/main/resources/yunnan_city_polygon.xml");
			Document doc2 = builder.parse(f2);
			NodeList polygonNames = doc2.getElementsByTagName("name");
			int id = 0;
			for(int po = 0 ; po < polygonNames.getLength(); po ++) {
				for(AreaModel ct : cityList) {
					if(polygonNames.item(po).getTextContent().equals(ct.getName())) {
						String name = polygonNames.item(po).getTextContent();
						NodeList placemarkChildNodes = polygonNames.item(po).getParentNode().getChildNodes();
						for(int y = 0 ; y < placemarkChildNodes.getLength() ; y++) {
							//如果一个地市只有一个多边形组成
							if("Polygon".equals(placemarkChildNodes.item(y).getNodeName())) {
								String[] points = placemarkChildNodes.item(y).getFirstChild().getFirstChild().getFirstChild().getTextContent().split("\n");
								List<Point.Double> polyLine = new ArrayList<Point.Double> ();
								String outply = "";
								for(String pt : points) {
									outply += pt.trim().substring(0, pt.length()-2) +  ";";
									String[] ptSpli = pt.split(",");
									if(ptSpli.length == 2) {
										Point.Double vertex = new Point.Double(Double.parseDouble(ptSpli[0]), Double.parseDouble(ptSpli[1])) ;
										polyLine.add(vertex);
									}
								}
								ct.setPolyLine(polyLine);
//								System.out.println("城市名称：" + name + "  中心点信息：" + ct.getCentre() + " 边界信息：" + outply.substring(0, outply.length()-1));
								
								String outPutStr = id + "\t" + ct.getAdCode() + "\t" + ct.getCityCode() + "\t" + ct.getCentre().getX() + "," + ct.getCentre().getY()
										+ "\t" + "city" + "\t" + "中国"+ "\t" + "云南省"  + "\t" +ct.getName() +"\t" + outply.substring(0, outply.length()-1) + "\r\n";
								out.write(outPutStr.getBytes("utf-8"));
								id ++;
							}
							//如果一个地市由两个多边形组成，输出两条记录
							if("MultiGeometry".equals(placemarkChildNodes.item(y).getNodeName())) {
								NodeList MultiGeometryChildNodes = placemarkChildNodes.item(y).getChildNodes();
								for(int m = 0 ; m < MultiGeometryChildNodes.getLength() ; m++) {
									if("Polygon".equals(MultiGeometryChildNodes.item(m).getNodeName())) {
										String[] points = MultiGeometryChildNodes.item(m).getFirstChild().getFirstChild().getFirstChild().getTextContent().split("\n");
										List<Point.Double> polyLine = new ArrayList<Point.Double> ();
										String outply = "";
										for(String pt : points) {
											outply += pt.trim().substring(0, pt.length()-2) +  ";";
											String[] ptSpli = pt.split(",");
											if(ptSpli.length == 3) {
												Point.Double vertex = new Point.Double(Double.parseDouble(ptSpli[0]), Double.parseDouble(ptSpli[1])) ;
												polyLine.add(vertex);
											}
										}
										ct.setPolyLine(polyLine);
//										System.out.println("城市名称：" + name + "  中心点信息：" + ct.getCentre() + " 边界信息：" + outply.substring(0, outply.length()-1));
										
										String outPutStr = id + "\t" + ct.getAdCode() + "\t" + ct.getCityCode() + "\t" 
										+ (ct.getCentre().getX() + Double.parseDouble("0.0" + id)) + "," //中心点偏差，防止按距离排序时将两个多边形之一去重
										+ (ct.getCentre().getY() + Double.parseDouble("0.0" + id))+ "\t" //中心点偏差，防止按距离排序时将两个多边形之一去重
										+ "city" + "\t" + "中国"+ "\t" + "云南省"  + "\t" +ct.getName() +"\t" + outply.substring(0, outply.length()-1) + "\r\n";
										out.write(outPutStr.getBytes("utf-8"));
										id ++;
									}
								}
							}
						}
					}
				}
			}
			
			out.close();
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		System.out.println("job done, boss");
	}

	
}
